<script setup lang="ts">
import { useMessage } from 'naive-ui'
import { computed, nextTick, ref } from 'vue'
import { Close } from '@vicons/ionicons5'
import { sleep } from 'radash'

const props = defineProps<{
  img1Src: string
  img2Src: string
}>()

const message = useMessage()
const options = [
  {
    label: '旋转图片',
    key: 'transform',
  },
]

const showDropdown = ref(false)
const x = ref(0)
const y = ref(0)
const showImg = ref(false)
const selectedImg = computed(() => {
  const half = window.innerWidth / 2
  return x.value >= half ? props.img1Src : props.img2Src
})
const working = computed(() => showDropdown.value || showImg.value)
const handleSelect = (key: string | number) => {
  console.log('🚀 ~ handleSelect ~ key:', key)
  showDropdown.value = false
  showImg.value = true
}

const handleContextMenu = (e: MouseEvent) => {
  e.preventDefault()
  showDropdown.value = false
  nextTick().then(() => {
    showDropdown.value = true
    x.value = e.clientX
    y.value = e.clientY
  })
}
const onClickoutside = () => {
  message.info('clickoutside')
  showDropdown.value = false
}

const closeModal = () => {
  sleep(50).then(() => {
    showImg.value = false
  })
}

defineExpose({
  working,
  showDropdown,
  handleContextMenu,
  closeModal,
})
</script>

<template>
  <n-dropdown
    placement="bottom-start"
    trigger="manual"
    :x="x"
    :y="y"
    :options="options"
    :show="showDropdown"
    :on-clickoutside="onClickoutside"
    @select="handleSelect"
  />

  <n-modal v-model:show="showImg" :mask-closable="false" transform-origin="center">
    <div class="modal-content">
      <div class="modal-header">
        <n-button text @click="closeModal">
          <n-icon size="24">
            <Close />
          </n-icon>
        </n-button>
      </div>
      <div class="image-container">
        <img :src="selectedImg" class="rotateImg" alt="旋转后的图片" />
      </div>
    </div>
  </n-modal>
</template>

<style scoped>
.modal-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  background-color: rgba(0, 0, 0, 0.8);
  position: fixed;
  top: 0;
  left: 0;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: flex-end;
  padding: 16px;
  flex-shrink: 0;
}

.image-container {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  padding: 20px;
}

.rotateImg {
  object-fit: contain;
  transform: rotate(90deg);
  transition: ease-in 0.3s;
  max-width: 100%;
  max-height: 100%;
  width: auto;
  height: auto;
}
</style>
